from django.contrib import admin, messages
from django.contrib.admin import helpers
from django.contrib.auth.admin import UserAdmin as DjangoUserAdmin
from django.shortcuts import render
from django.utils.translation import gettext_lazy as _
from django.utils.html import format_html
from .models import User, InviteCode
from .views import generate_invite_code, generate_invite_codes

@admin.register(User)
class UserAdmin(DjangoUserAdmin):
    fieldsets = (
        (None, {"fields": ("phone_number", "username", "password")}),
        (_("Personal info"), {"fields": ("avatar", "nickname", "real_name", "email")}),
        (
            _("Permissions"),
            {
                "fields": (
                    "is_active",
                    "is_staff",
                    "is_superuser",
                    "groups",
                    "user_permissions",
                ),
            },
        ),
        (_("Important dates"), {"fields": ("last_login", "date_joined")}),
    )
    list_display = ("nickname", "real_name", "phone_number", "email", "is_staff")
    search_fields = ("nickname", "real_name", "phone_number", "username", "email")
    actions = ["cancel_users"]
    ordering = (
        "-is_active",
        "-date_joined",
    )

    def get_actions(self, request):
        actions = super().get_actions(request)
        if 'delete_selected' in actions:
            del actions['delete_selected']
        return actions

    @admin.action(description="注销用户")
    def cancel_users(self, request, queryset):
        if request.POST.get("post"):
            queryset = self.model.objects.filter(
                pk__in=request.POST.getlist(helpers.ACTION_CHECKBOX_NAME)
            )
            n = len(queryset)
            if n:
                try:
                    queryset.cancel_users()
                except Exception as e:
                    self.message_user(request, f"注销失败。{e}", messages.ERROR)
                else:
                    self.message_user(request, f"成功注销 {n} 个用户", messages.SUCCESS)
            return None
        context = {
            **self.admin_site.each_context(request),
            "title": "注销用户",
            "objects": queryset,
            "model_count": {"用户": len(queryset)},
            "queryset": queryset,
            "opts": self.model._meta,
        }
        return render(request, "admin/user/cancel_selected_confirmation.html", context)

@admin.register(InviteCode)
class InviteCodeAdmin(admin.ModelAdmin):
    list_display = ('code', 'creator_link', 'used_by_link', 'created_at', 'used_at', 'status')
    list_filter = ('created_at', 'used_at')
    search_fields = ('code', 'creator__username', 'creator__nickname', 'used_by__username', 'used_by__nickname')
    ordering = ('-created_at',)
    readonly_fields = ('code', 'created_at', 'used_at')
    exclude = ('code',)  # 在编辑表单中隐藏code字段
    
    def get_queryset(self, request):
        return super().get_queryset(request).select_related('creator', 'used_by')
    
    def creator_link(self, obj):
        if obj.creator:
            return format_html('<a href="{}">{}</a>',
                             f"../user/{obj.creator.id}/change/",
                             obj.creator.nickname or obj.creator.username)
        return "-"
    creator_link.short_description = "创建者"
    
    def used_by_link(self, obj):
        if obj.used_by:
            return format_html('<a href="{}">{}</a>',
                             f"../user/{obj.used_by.id}/change/",
                             obj.used_by.nickname or obj.used_by.username)
        return "-"
    used_by_link.short_description = "使用者"
    
    def status(self, obj):
        if obj.used_by:
            return format_html('<span style="color: #666;">已使用</span>')
        return format_html('<span style="color: green;">可用</span>')
    status.short_description = "状态"
    
    actions = ['generate_new_codes']
    
    def save_model(self, request, obj, form, change):
        if not change:  # 只在创建新记录时生成邀请码
            obj.code = generate_invite_code()
        super().save_model(request, obj, form, change)
    
    @admin.action(description='为选中的用户生成10个新邀请码')
    def generate_new_codes(self, request, queryset):
        creators = set(queryset.values_list('creator_id', flat=True))
        count = 0
        for creator_id in creators:
            user = User.objects.get(id=creator_id)
            generate_invite_codes(user)
            count += 1
        self.message_user(request, f'成功为{count}个用户生成了新的邀请码')
    
    def has_change_permission(self, request, obj=None):
        # 禁止编辑已有的邀请码
        return False